define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

	var Controller = {
		index  : function () {
		// 初始化表格参数配置
			Table.api.init();

			//绑定事件
			$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
				var panel = $($(this).attr("href"));
				if (panel.length > 0) {
					Controller.table[panel.attr("id")].call(this);
					$(this).on('click', function (e) {
						$($(this).attr("href")).find(".btn-refresh").trigger("click");
					});
				}
				//移除绑定的事件
				$(this).unbind('shown.bs.tab');
			});

			//必须默认触发shown.bs.tab事件
			$('ul.nav-tabs li.active a[data-toggle="tab"]').trigger("shown.bs.tab");
			let q = {}
			location.search.replace(/([^?&=]+)=([^&]+)/g,function(_,k,v){q[k]=v});
			if (q.active) {
				$('ul.nav-tabs li .'+q.active).trigger("click");
			}
			// 初始化表格参数配置
			Table.api.init({
				extend : {
					add_url    : 'qingdongams/customer/receivables/add',
					detail_url : 'qingdongams/customer/receivables/detail',
					customer_url : 'qingdongams/customer/customer/detail',
					contract_url : 'qingdongams/customer/contract/detail',
					table      : 'customer',
				}
			});
			$(document).on('click', '.show-detail', function (data) {
				var area = [$(window).width() > 1200 ? '1200px' : '95%', $(window).height() > 800 ? '800px' : '95%'];
				var options = {
					shadeClose : false,
					shade      : [0.3, '#393D49'],
					area       : area,
					callback   : function (value) {
						//在回调函数里可以调用你的业务代码实现前端的各种逻辑和效果
						console.log(value);
					}
				};
				Fast.api.open($.fn.bootstrapTable.defaults.extend.detail_url+"?ids="+$(this).data('id'), '回款详情', options);
			}).on('click', '.show-customer', function (data) {
				var area = [$(window).width() > 1200 ? '1200px' : '95%', $(window).height() > 800 ? '800px' : '95%'];
				var options = {
					shadeClose : false,
					shade      : [0.3, '#393D49'],
					area       : area,
					callback   : function (value) {
						//在回调函数里可以调用你的业务代码实现前端的各种逻辑和效果
						console.log(value);
					}
				};
				Fast.api.open($.fn.bootstrapTable.defaults.extend.customer_url + "?ids=" + $(this).data('id'), '客户详情', options);
			}).on('click', '.show-contract', function (data) {
				var area = [$(window).width() > 1200 ? '1200px' : '95%', $(window).height() > 800 ? '800px' : '95%'];
				var options = {
					shadeClose : false,
					shade      : [0.3, '#393D49'],
					area       : area,
					callback   : function (value) {
						//在回调函数里可以调用你的业务代码实现前端的各种逻辑和效果
						console.log(value);
					}
				};
				Fast.api.open($.fn.bootstrapTable.defaults.extend.contract_url + "?ids=" + $(this).data('id'), '订单详情', options);
			}).on('click','.btn-imports',function () {
				Fast.api.open("qingdongams/customer/receivables/import", "回款导入",{
					shadeClose: false,
					shade: false,
					maxmin: false,
					moveOut: false,
					scrollbars:false,
					'area':[
						$(window).width() > 800 ? '600px' : '400px',
						$(window).height() > 600 ? '500px' : '400px'
					],
					callback:function(value){
						Form.events.plupload("#plupload-local");

						//   在这里可以接收弹出层中使用`Fast.api.close(data)`进行回传数据
					},
				});

			}).on("click", ".btn-export", function () {
				var tab_id=$('.active.in').attr('id');
				var table,type;
				switch (tab_id){
					case 'first'://全部
						table=$('#table');
						type=0;
						break;
					case 'second'://我负责的
						table=$('#table1');
						type=1;
						break;
					case 'third'://下属负责的
						table=$('#table2');
						type=2;
						break;
				}
				var ids = Table.api.selectedids(table);
				var page = table.bootstrapTable('getData');
				var options = table.bootstrapTable('getOptions');
				var params=options.queryParams({});
				var all = options.totalRows;
				var sort = options.sortName+' '+options.sortOrder;
				var filter = params.filter;
				var op = params.op;

				Layer.confirm("请选择导出的选项", {
					title   : '导出数据',
					btn     : ["选中项(" + ids.length + "条)", "本页(" + page.length + "条)", "全部(" + all + "条)"],
					success : function (layero, index) {
						$(".layui-layer-btn a", layero).addClass("layui-layer-btn0");
					}, yes   : function (index, layero) {
						if (ids.length == 0) {
							Layer.alert('数据为空');
							return true;
						}
						$.post('qingdongams/customer/receivables/export', {sort:sort,ids : ids.join(","), isall : 1}, function (res) {
							Layer.alert(res.msg);
							if(res.code == 1){
								window.location.href = res.data.filePath;
								Layer.close(index);
							}
							table.bootstrapTable('refresh');
						}, 'json');
						return false;
					},
					btn2    : function (index, layero) {
						if (page.length == 0) {
							Layer.alert('数据为空');
							return true;
						}
						var ids = [];
						$.each(page, function (i, j) {
							ids.push(j.id);
						});
						$.post('qingdongams/customer/receivables/export', {sort:sort,ids : ids.join(","), isall : 2}, function (res) {
							Layer.alert(res.msg);
							if(res.code == 1){
								window.location.href = res.data.filePath;
								Layer.close(index);
							}
							table.bootstrapTable('refresh');
						}, 'json');
						return false;
					},
					btn3    : function (index, layero) {
						if (page.length == 0) {
							Layer.alert('数据为空');
							return true;
						}
						$.post('qingdongams/customer/receivables/export?filter='+filter+'&op='+op, {sort:sort,ids : ids.join(","), isall : 3,type:type}, function (res) {
							Layer.alert(res.msg);
							if(res.code == 1){
								window.location.href = res.data.filePath;
								Layer.close(index);
							}
							table.bootstrapTable('refresh');
						}, 'json');
						return false;
					}
				})
			});
		},
		table: {
			first: function () {

				// 初始化表格参数配置
				Table.api.init({});
				if(Config.fields !='[]'){
					if (Config.fields && Object.keys(Config.fields).length > 0) {
						var fields = JSON.parse(Config.fields);
						var start = Controller.tableinfo.columns[0].length-2;
						for (var i = 0; i < fields.length; i++) {
							if (fields[i].hasOwnProperty('formatter'))
								fields[i].formatter = eval(fields[i].formatter);
							if (fields[i].hasOwnProperty('events'))
								fields[i].events = eval(fields[i].events);
							if (fields[i].hasOwnProperty('searchList'))
								fields[i].searchList = JSON.parse(fields[i].searchList);
							Controller.tableinfo.columns[0].splice(start + i, 0, fields[i]);
						}
					}
				}


				var table = $("#table");
				Controller.tableinfo.url=location.href+'&type=0';
				Controller.tableinfo.toolbar='#toolbar';
				Controller.tableinfo.columns[0][Controller.tableinfo.columns[0].length-1].table=table;

				// 初始化表格
				table.bootstrapTable(Controller.tableinfo);

				// 为表格绑定事件
				Table.api.bindevent(table);
			},
			second: function () {
				// 初始化表格参数配置
				Table.api.init({});


				var table = $("#table1");
				Controller.tableinfo.url=location.href+'&type=1';
				Controller.tableinfo.toolbar='#toolbar1';
				Controller.tableinfo.columns[0][Controller.tableinfo.columns[0].length-1].table=table;

				// 初始化表格
				table.bootstrapTable(Controller.tableinfo);

				// 为表格绑定事件
				Table.api.bindevent(table);
			},
			third: function () {
				// 初始化表格参数配置
				Table.api.init({});
				var table = $("#table2");
				Controller.tableinfo.url=location.href+'&type=2';
				Controller.tableinfo.toolbar='#toolbar2';
				Controller.tableinfo.columns[0][Controller.tableinfo.columns[0].length-1].table=table;

				// 初始化表格
				table.bootstrapTable(Controller.tableinfo);
				// 为表格绑定事件
				Table.api.bindevent(table);
			},
		},
		tableinfo:{
			url          : '',
			toolbar: '#toolbar',
			pk           : 'id',
			sortName     : 'id',
			fixedColumns : true,
			fixedNumber  : 2,
			search:false,
			searchFormVisible:true,
			columns      : [
				[
					{checkbox : true},
					{
						field : 'number', title : '预约订单编号', fixedColumns : true, formatter : function (value, row, index) {

							return "<a href='javascript:void(0);' data-id='" + row.id + "' class='show-detail'>" + value + "</a>";
						},operate: 'LIKE'
					},
					{field : 'customer', title : '客户', fixedColumns : true, formatter : function (value, row, index) {
							if(row.customer){
								return "<a href='javascript:void(0);' data-id='" + row.customer_id + "' class='show-customer'>" + row.customer.name + "</a>";
							}
							return '';
						},operate:false},
					{field : 'customer_id', title : '客户名称', visible: false, addClass: "selectpage", extend: "data-source='qingdongams/customer/customer/index' data-field='name'"},
					{field : 'user.name', title : '平台会员',operate:'like'},
					{field : 'jigou.jigou_name', title : '所属机构',operate:'like'},
					{field : 'contract_id', title : '支付订单编号', formatter : function (value, row, index) {
							if(row.contract){
								return "<a href='javascript:void(0);' data-id='" + row.contract_id + "' class='show-contract'>" + row.contract.num + "</a>";
							}
							return '';
						},operate:false},
					{field : 'return_time', title : '核销日期',operate: 'RANGE', addclass: 'datetimerange'},
					{field : 'return_type', title : '回款方式',operate:'like'},
					{field : 'money', title : '核销金额',operate:'like'},
					{field : 'owner_staff.name', title : '负责人',operate:false},
					{field : 'owner_staff_id', title : '负责人', visible: false, addClass: "selectpage", extend: "data-source='qingdongams/department/staff/index' data-field='name'"},

					{field : 'check_status', title : '审核状态',formatter:Table.api.formatter.status, searchList: {0:'待审核', 2:'审核通过',3:"审核未通过",1: '审核中',4:"撤销"},custom: {0: 'gray', 1: 'gray',2: 'success', 3: 'danger'}},
					{field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},

				]
			],
			onLoadSuccess:function(){
				// 这里就是数据渲染结束后的回调函数
				$(".btn-add").data("area",["80%","80%"]);
				$(".btn-edit").data("area",["80%","80%"]);
			}
		},
		add    : function () {

			Controller.api.bindevent();
		},
		import    : function () {
			Controller.api.bindevent();
		},
		detail : function () {
			// 初始化表格参数配置
			Table.api.init({});
			$('.stafflist').popover({
				placement : 'bottom',
				trigger : 'hover'
			});
			//操作日志
			var table2 = $("#operation_log");
			// 初始化表格
			table2.bootstrapTable({
				url          : 'qingdongams/examine/examine/receivables?receivables_id='+Config.idinfo.id,
				pk           : 'id',
				sortName     : 'id',
				operate      : false,
				commonSearch : false,
				search       : false,
				visible      : false,
				showColumns  : false,
				showExport   : false,
				showToggle   : false,
				columns      : [
					[
						{field: 'check_staff.name', title: __('审批人')},
						{field: 'status', title: __('审批状态'), operate: false, formatter: Table.api.formatter.status,  searchList: {0: __('待审批'), 1: __('审批通过'), 2: __('审批拒绝'), 3: __('撤销')}},
						{field: 'check_time', title: __('审批时间'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
						{field: 'content', title: __('内容'),cellStyle:function (value,row,index,field) {
								return {
									css: {
										"min-width": "150px",
										"white-space": "nowrap",
										"text-overflow": "ellipsis",
										"overflow": "hidden",
										"max-width":"300px",
										'cursor':"pointer"
									}
								};
							},formatter:function (value,row,index,field) {
								var span=document.createElement('span');
								span.setAttribute('title',value);
								span.innerHTML = value;
								return span.outerHTML;
							}
						},
						{field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},

					]
				]
			});

			Controller.api.bindevent();
		},
		api    : {
			bindevent : function () {
				$(document).on("click", ".select-customer", function(){
					var $this=$(this);
					top.Fast.api.open($(this).data("url") , __('Select'), {callback: function (data) {
							$this.html(data.name);
							$('[name="'+$this.data('name')+'"]').val(data.id);
						},area:["100%", "100%"]});
				}).on("click", ".select-contract", function(){
					var $this=$(this),customer_id=$('[name="row[customer_id]"]').val();
					if(!customer_id){
						Layer.msg('请先选择客户');
						return false;
					}
					top.Fast.api.open($(this).data("url")+"&customer_id="+customer_id , __('Select'), {callback: function (data) {
							$this.html(data.name);
							$('[name="'+$this.data('name')+'"]').val(data.id);
							$.post('qingdongams/customer/receivables/plan', {customer_id:customer_id,contract_id : data.id}, function (res) {
								$('#plan_id').html('');
								var data = res.data;
								var length = data.length;
								var html='';
								for (var i = 0; i < length; i++) {
									html += '<option value="' + data[i].id + '">' + data[i].num + '</option>';
								}
								$('#plan_id').html(html);
								$('#plan_id').selectpicker('refresh');

							}, 'json');
						},area:["100%", "100%"]});
				});

				$("#c-contract_id").data("params", function (obj) {
					var customer_id=$('#c-customer_id').val();
					return {customer_id: customer_id};
				});

				require(['backend/qingdongams/common/common'])
				Form.api.bindevent($("form[role=form]"));
			}
		}
	};
	return Controller;
});